import React from 'react'
import {Menu, Icon} from 'antd';
import {Link} from 'dva/router';
import {arrayToTree} from '../../utils/utils';
import pathToRegexp from 'path-to-regexp'
import styles from './CMenu.less'

const {Item, SubMenu} = Menu;

export default class CMenu extends React.PureComponent {

  constructor(props) {
    super(props);

    this.mainNavList = props.mainNavList;
    this.navTree = arrayToTree(this.mainNavList.filter(item => item.visible !== false), 'id', 'pid');
    this.state = {
      openKeys: this.getCurrentSubMenus(),
    };
  }

  getCurrentNavItem() {
    let currentNavItem;
    for (let item of this.mainNavList) {
      if (item.path && pathToRegexp(item.path).exec(this.props.location.pathname)) {
        currentNavItem = item;
        break;
      }
    }
    return currentNavItem;
  }

  getNavItem(id) {
    let navItem = null;
    for (let item of this.mainNavList) {
      if (item.id === id) {
        navItem = item;
        break;
      }
    }
    return navItem;
  }

  getCurrentSubMenus() {
    let subMenus = [];
    let currentSubMenu = '';
    const currentNavItem = this.getCurrentNavItem();
    if (currentNavItem) {
      if (currentNavItem.visible !== false) {
        currentSubMenu = currentNavItem.pid.toString();
      } else {
        const parentNavItem = this.getNavItem(currentNavItem.pid);
        currentSubMenu = parentNavItem.pid.toString();
      }
      subMenus.push(currentSubMenu);
    }
    return subMenus;
  }

  getCurrentSelectedKeys() {
    let selectedKeys = [];
    const currentNavItem = this.getCurrentNavItem();
    if (currentNavItem) {
      selectedKeys.push(currentNavItem.visible !== false ? currentNavItem.id.toString() : currentNavItem.pid.toString());
    }
    return selectedKeys;
  }

  getMenuItems(navTree) {
    if (!navTree) {
      return [];
    }
    return navTree.map(item => {
      if (!item.name) {
        return null;
      }
      let itemPath;
      if (item.path.indexOf('http') === 0) {
        itemPath = item.path;
      } else {
        itemPath = `/${item.path || ''}`.replace(/\/+/g, '/');
      }
      if (item.children && item.children.some(child => child.name)) {
        return (
          <SubMenu
            key={item.key || item.id}
            title={
              item.icon
                ? <span>
									<Icon type={item.icon}/>
									<span>{item.name}</span>
								</span>
                : item.name
            }
          >
            {this.getMenuItems(item.children)}
          </SubMenu>
        );
      }
      const icon = item.icon && <Icon type={item.icon}/>;
      return (
        <Item key={item.key || item.id}>
          {
            /^https?:\/\//.test(itemPath)
              ? <a href={itemPath} target={item.target}>
                {icon}<span>{item.name}</span>
              </a>
              : <Link
                to={itemPath}
                target={item.target}
                replace={itemPath === this.props.location.pathname}
              >
                {icon}<span>{item.name}</span>
              </Link>
          }
        </Item>
      );
    });
  }

  handleOpenChange = (openKeys) => {
    const lastOpenKey = openKeys[openKeys.length - 1];
    this.setState({
      openKeys: [lastOpenKey],
    });
  };

  render() {
    const {lightTheme, collapsed} = this.props;
    const menuProps = collapsed
      ? {}
      : {
        onOpenChange: this.handleOpenChange,
        openKeys: this.state.openKeys,
      };

    return (
      <Menu
        mode="inline"
        theme={lightTheme ? "light" : "dark"}
        className={styles.menu}
        selectedKeys={this.getCurrentSelectedKeys()}
        {...menuProps}
      >
        {this.getMenuItems(this.navTree)}
      </Menu>
    );
  }
}
